<template>
  <div class="searchSuggest">
    <div class="title">搜索"{{ keywords }}"</div>
    <ul>
      <li v-for="item in suggestList" :key="item.id"  @click="$emit('suggest', item.name)">
        <i></i><span>{{ item.name }}</span>
      </li>
    </ul>
    <Loading v-if="showLoading"></Loading>
    <div class="noRes" v-if="noRes">无匹配结果</div>
  </div>
</template>

<script>
import Loading from "./Loading.vue";
export default {
  components: { Loading },
  data() {
    return {
      showLoading: false,
      suggestList: null,
      suggestT: null,
      noRes: false,
    };
  },
  props: {
    keywords: {
      type: String,
      default: "",
    },
  },
  watch: {
    keywords(val) {
      this.getSuggest(val);
    },
  },
  created() {
    this.getSuggest(this.keywords);
  },
  methods: {
    getSuggest(keyword) {
      this.showLoading = true;
      this.suggestList = [];
      this.noRes = false;
      clearTimeout(this.suggestT);
      this.suggestT = setTimeout(() => {
        this.$http
          .get("/search/suggest", {
            params: {
              keywords: keyword,
            },
          })
          .then((d) => {
            let order = d.data.result.order;
            let result = [];
            for (let i = 0; i < order.length; i++) {
              result = result.concat(d.data.result[order[i]]);
            }
            this.suggestList = result;
            this.showLoading = false;
          }, 500)
          .catch(() => {
            this.suggestList = [];
            this.noRes = true;
            this.showLoading = false;
          });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.title {
  height: 50px;
  margin-left: 10px;
  padding-right: 10px;
  font-size: 15px;
  line-height: 50px;
  color: #5F9EA0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: normal;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}
ul {
  li {
    display: flex;
    align-items: center;
    height: 45px;
    padding-left: 10px;
    i {
      margin-right: 7px;
      width: 15px;
      height: 15px;
      background-image: url();
    }
    span {
      display: inline-block;
      flex: 1;
      // width: 1%;
      padding-right: 10px;
      font-size: 15px;
      line-height: 45px;
      color: #333;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: normal;
      border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    }
  }
}
.noRes {
  height: 50px;
  padding-right: 10px;
  font-size: 15px;
  text-align: center;
  line-height: 50px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: normal;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}
</style>
